package com.example;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * zookeeper client test
 */
public class ZookeeperClientTest {

    // 等待时间
    private static final int sessionTimeout = 2000;
    // 主机名
    private static final String connectString = "Cent7:2181,Cent7-c1:2181,Cent7-c2:2181";
    // zookeeper
    private ZooKeeper zkClient = null;

    /**
     * 初始化zookeeper，依赖junit的@Before注解
     *
     * @throws Exception the exception
     */
    @Before
    public void init() throws Exception {

        zkClient = new ZooKeeper(connectString, sessionTimeout, watchedEvent -> {

        });
    }

    /**
     * 创建节点,需要先初始化zookeeper,否则zkClient为null
     *
     * @throws InterruptedException the interrupted exception
     * @throws KeeperException      the keeper exception
     */
    @Test
    public void create() throws InterruptedException, KeeperException {
        // 形参：1.节点名以及位置 2.节点携带的数据 3.节点的权限（任何人可访问） 4.节点的类型（持久型）
        zkClient.create("/example", "HelloWorld".getBytes(StandardCharsets.UTF_8), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

    }

    /**
     * 判断节点是否存在
     *
     * @throws InterruptedException the interrupted exception
     * @throws KeeperException      the keeper exception
     */
    @Test
    public void isExist() throws InterruptedException, KeeperException {

        Stat exists = zkClient.exists("/hhh", false);
        System.out.println(exists == null ? "不存在" : "存在");
    }

    /**
     * 获取并监听子节点，新增操作必须是增加根节点的子节点，比如：create /baba "baba"，否则除第一次外，将不会打印，
     *
     * @throws InterruptedException the interrupted exception
     * @throws KeeperException      the keeper exception
     */
    @Test
    public void getChildren() throws InterruptedException, KeeperException {

        List<String> children = null;
        List<String> temp;
        int count = 1;

        while (true) {

            temp = children;
            children = zkClient.getChildren("/", true);

            if (temp == null || temp.size() != children.size()) {
                System.out.println("--- 第" + count++ + "次监听到变化 ---");
                children.forEach(System.out::println);

            }
        }
    }

}
